<?php
/*
* 2007-2011 PrestaShop 
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
*  @author PrestaShop SA <contact@prestashop.com>
*  @copyright  2007-2011 PrestaShop SA
*  @version  Release: $Revision: 6594 $
*  @license    http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
*/

/* SSL Management */
$useSSL = true;

include(dirname(__FILE__).'/../../config/config.inc.php');
include(dirname(__FILE__).'/../../header.php');
include_once(dirname(__FILE__).'/groupbuyingreg.php');
include_once(dirname(__FILE__).'/myregistration.php');
include_once(dirname(__FILE__).'/GroupBuyingRegModule.php');

$errors = array();

if ($cookie->isLogged())
{
	if (Tools::getValue('action') == 'edit' OR Tools::getValue('action') == 'delete')
	{
		if (!$id_group_buying_registration = (int)(Tools::getValue('id_group_buying_registration')))
			$errors[] = Tools::displayError('You must have registered for a group buying promotion to edit / delete.');
		
		if (Tools::getValue('action') == 'delete')
		{
			if (!GroupBuyingRegModule::deleteRegistrationByRegId((int)($id_group_buying_registration)))
				$errors[] = Tools::displayError('There is an error when you try to update your registration.');
				
			if (!$errors)
				Tools::redirect('modules/groupbuyingreg/myregistrations.php');
		}
	}
	
	/* Security Key */	
	$codelen = 5;
	$rnd = mt_rand(1, pow(10,$codelen));
	$badSecKey = false;
	$_POST['staf_rnd'] = (int)$_POST['staf_rnd'];
	$_POST['staf_skey'] = (int)$_POST['staf_skey'];
	if (extension_loaded("gd")) {
		$datekey = date("F j");
		$rcode = hexdec(md5($_SERVER['HTTP_USER_AGENT'].'1'.$_POST['staf_rnd'].$datekey));
		$code = substr($rcode,4,$codelen);
	}else{
		// no GD (image library), so let in
		$code = $_POST['staf_skey'];
	}
	if ($_POST['staf_skey']!=$code)
		$badSecKey = true;
			
	if (Tools::isSubmit('submitUpdateReg'))
	{
		if (Tools::getValue('group_buying_company'))
			$selectedCompanies = (int)Tools::getValue('group_buying_company');
		if (Tools::getValue('group_buying_promotion'))
			$selectedPromotions = (int)Tools::getValue('group_buying_promotion');
		//Error checking
		if (!$id_group_buying_company = Tools::getValue('group_buying_company'))
			$errors[] = Tools::displayError('You must select a group buying company.');
		elseif (!$id_group_buying_promotion = Tools::getValue('group_buying_promotion'))
			$errors[] = Tools::displayError('You must select a corresponding promotion.');
		elseif (!$coupon_codes = Tools::getValue('group_buying_coupon_code'))
			$errors[] = Tools::displayError('You must enter a coupon code.');
		elseif ($badSecKey)
			$errors[] = Tools::displayError('The 5 digit Security Code doesn\'t match.');
		elseif (!GroupBuyingRegModule::isValidPromotion($id_group_buying_company, $id_group_buying_promotion))
			$errors[] = Tools::displayError('The selected group buying company does not offer the promotion you selected');
		else
		{
			// if registration exists, then insert, else update
			if (!$id_group_buying_registration = Tools::getValue('id_group_buying_registration'))
			{
				$reg = new GroupBuyingRegModule();
				$reg->id_customer = (int)($cookie->id_customer);
				$reg->id_group_buying_company = (int)($id_group_buying_company);
				$reg->id_group_buying_promotion = (int)($id_group_buying_promotion);
				$reg->coupon_codes = $coupon_codes;
				if (!$reg->validateFields(false))
					return false;
				else
					$reg->save();
				
				//$data = array('{firstname}' => $newCustomer->firstname, '{lastname}' => $newCustomer->lastname, '{group_buying_company}' => $groupBuyingCompany, '{coupon_codes}' => $couponCodes);
				//Mail::Send((int)$cookie->id_lang, 'registration_success', Mail::l('Congratulations!', (int)($cookie->id_lang)), $data, $newCustomer->email, $newCustomer->firstname.' '.$newCustomer->lastname, strval(Configuration::get('PS_SHOP_EMAIL')), strval(Configuration::get('PS_SHOP_NAME')), NULL, NULL, dirname(__FILE__).'/mails/');
			}
			else
			{
				// Update the existing one
				if (!GroupBuyingRegModule::setRegistrationByRegId((int)($id_group_buying_registration), (int)($id_group_buying_company), (int)($id_group_buying_promotion), $coupon_codes))
					$errors[] = Tools::displayError('There is an error when you try to update your registration.');
			}
		}
		if (!$errors)
			Tools::redirect('modules/groupbuyingreg/myregistrations.php');
	}
	$smarty->assign(array(
		'group_buying_companies' => (GroupBuyingRegModule::getGroupBuyingCompanies((int)$cookie->id_lang)),
		'group_buying_promotions' => (GroupBuyingRegModule::getAllGroupBuyingPromotions((int)$cookie->id_lang)),
		'id_group_buying_company' => GroupBuyingRegModule::getCompanyIdByRegId((int)$id_group_buying_registration),
		'id_group_buying_registration' => (int)$id_group_buying_registration,
		'id_group_buying_promotion' => GroupBuyingRegModule::getPromotionIdByRegId((int)$id_group_buying_registration),
		'coupon_codes' => GroupBuyingRegModule::getCouponCodeByRegId((int)$id_group_buying_registration),
		'sl_company' => (isset($selectedCompanies) ? $selectedCompanies : '-'),
		'sl_promotion' => (isset($selectedPromotions) ? $selectedPromotions : '-'),
		'staf_rnd' => $rnd,
		'staf_codelen' => $codelen
	));	
}
else
	Tools::redirect('authentication.php?back=modules/groupbuyingreg/updateregistration.php');
	//$errors[] = Tools::displayError('You must be logged in to manage your registrations.'); 

$smarty->assign(array(
	'id_customer' => (int)($cookie->id_customer),
	'errors' => $errors
));

if (Tools::file_exists_cache(_PS_THEME_DIR_.'modules/groupbuyingreg/updateregistration.tpl'))
	$smarty->display(_PS_THEME_DIR_.'modules/groupbuyingreg/updateregistration.tpl');
elseif (Tools::file_exists_cache(dirname(__FILE__).'/updateregistration.tpl'))
	$smarty->display(dirname(__FILE__).'/updateregistration.tpl');
else
	echo Tools::displayError('No template found');

include(dirname(__FILE__).'/../../footer.php');
